import React, { Component } from 'react';

let state = {
  todos: [{
    text: 'Eat food',
    completed: true,
    id: new Date().getTime() + '' + parseInt(Math.random() * 10000),
  }, {
    text: 'Exercise',
    completed: false,
    id: new Date().getTime() + '' + parseInt(Math.random() * 10000),
  }],
  visibilityFilter: 'SHOW_COMPLETED'
}

function visibilityFilter(state = 'SHOW_ALL', action) {
  if (action.type === 'SET_VISIBILITY_FILTER') {
    return action.filter;
  } else {
    return state;
  }
}

function todos(state = [], action) {
  switch (action.type) {
  case 'ADD_TODO':
    return state.concat([{
      text: action.text,
      completed: false,
      id: new Date().getTime() + '' + parseInt(Math.random() * 10000)
    }]);
  case 'TOGGLE_TODO':
    return state.map((todo, index) =>
      action.index === index ?
        { text: todo.text, completed: !todo.completed, id: todo.id } :
        todo
   )
  default:
    return state;
  }
}

function todoApp(state = {}, action) {
  return {
    todos: todos(state.todos, action),
    visibilityFilter: visibilityFilter(state.visibilityFilter, action)
  };
}

export default class PureJsRedux extends Component {

  constructor(props) {
    super(props);
    this.state = {
      ...state,
      inputText: ''
    };
    console.log(state.todos)
  }

  toggle = (todo, index) => {
    state.todos = todos(state.todos, {
      type: 'TOGGLE_TODO',
      index,
    });
    this.setState({
      todos: state.todos,
    })
  }

  addTodo = () => {
    state.todos = todos(state.todos, {
      type: 'ADD_TODO',
      text: this.state.inputText,
    })
    this.setState({
      todos: state.todos,
      inputText: '',
    })
  }

  onInput = (e) => {
    console.log('inputText: ', e.target.value)
    this.setState({
      inputText: e.target.value,
    })
  }

  render() {
    return (
      <div>
        <h3>使用 React + JS ，按 Redux 思想实现 Todo List</h3>
        <ul>
          {
            this.state.todos.map((todo, index) => (
              <li
                key={todo.id}
                style={{textDecoration: todo.completed ? 'line-through' : 'inherit', marginTop: 6}}
              >
                <span>{todo.text}</span>
                <span style={{marginLeft: '6px'}}>{todo.completed ? '已完成' : '未完成'}</span>
                <button style={{marginLeft: '6px'}} onClick={() => this.toggle(todo, index)}>完成</button>
              </li>
            ))
          }
        </ul>
        <div style={{marginTop: 6}}>
          <input type="text" onChange={this.onInput} value={this.state.inputText} />
          <button onClick={this.addTodo}>增加</button>
        </div>
      </div>
    )
  }
}